//
//  EcgDetailVc.m
//  CareRingApp
//
//  Created by Linktop on 2024/4/9.
//

#import "EcgDetailVc.h"
#import <QMUIKit/QMUIKit.h>
#import <Masonry/Masonry.h>
#import "UIViewController+Custom.h"
#import "ConfigModel.h"
#import "ImgTitleItem.h"
#import "SubTitleItem.h"
#import "LTRingEcgDrawHistoryView.h"

#import "SepLineView.h"
#import "HMpdfManager.h"
#import "LTRingEcgDrawLineView.h"


@interface EcgDetailVc ()
@property(strong, nonatomic)UIScrollView *scrollView;
@property(strong, nonatomic) UIView *mainContent, *topCnt, *bottomCnt;
@property(strong, nonatomic) QMUIButton *deletebtn, *pdfBtn;

@property(strong, nonatomic) UILabel *topConcluLbl, *topDateLbl, *emercallTipLbl, *sampleTitleLbl, *conclusionDescLbl ,*symptomsDescLbl;

@property(assign, nonatomic)CGFloat horMargin;
@property(strong, nonatomic) ImgTitleItem *hrItem;

@property(strong, nonatomic) SubTitleItem *startTimeItem, *endTimeItem, *sourceItem, *firmwareItem;

@property(strong, nonatomic) LTRingEcgDrawHistoryView *hisDrawLineView;

@property(strong, nonatomic) HMpdfManager *pdfManager;
@property(strong, nonatomic) UIButton *infoBtn;


@end

@implementation EcgDetailVc

- (void)viewDidLoad {
    [super viewDidLoad];
    self.horMargin = 15.f;
    [self initUI];
    self.pdfManager = [[HMpdfManager alloc] init];

}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.scrollView.contentSize = CGSizeMake(self.scrollView.bounds.size.width, CGRectGetMaxY(self.mainContent.frame));

}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // 展示信息
    [self showRecInfo];
    
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    self.hisDrawLineView.drawLineView.direction = self.ecgRecord.wearHand;
    [self.hisDrawLineView drawAllData:self.ecgRecord.volArray];
}


-(void)showRecInfo {
    self.topConcluLbl.text = [DBEcgRecord titleOfConclusion:self.ecgRecord.conclusion];
    NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
    fmt.dateFormat = _L(L_ECG_DETAIL_DATEFMT);
    
    self.topDateLbl.text = [fmt stringFromDate:[NSDate dateWithTimeIntervalSince1970:self.ecgRecord.startTs.doubleValue ]];
    
    if (self.ecgRecord.avgHeartRate.intValue > 40) {
        self.hrItem.titleLbl.text = [NSString stringWithFormat:@"%@ %d%@", _L(L_AVG), self.ecgRecord.avgHeartRate.intValue, _L(L_UNIT_HR)];

    } else {
        self.hrItem.titleLbl.text = [NSString stringWithFormat:@"%@ %@%@", _L(L_AVG), NONE_VALUE, _L(L_UNIT_HR)];
    }
    
    // 症状描述
    self.conclusionDescLbl.text = [DBEcgRecord descOfConclusion:self.ecgRecord.conclusion];
    
    // 症状
    [self freshSymptomsDesc:_L(L_DETAIL_SYMPTOMS)];
    
    // 下半部分
    self.startTimeItem.subTitleLbl.text = [fmt stringFromDate:[NSDate dateWithTimeIntervalSince1970:self.ecgRecord.startTs.doubleValue ]];
    self.endTimeItem.subTitleLbl.text = [fmt stringFromDate:[NSDate dateWithTimeIntervalSince1970:self.ecgRecord.endTs.doubleValue ]];
    self.sourceItem.subTitleLbl.text = self.ecgRecord.isRingAlgorithm ? [ConfigModel appName]:@"" ;
    self.firmwareItem.subTitleLbl.text = [NSString stringWithFormat:@"V%@", self.ecgRecord.firmWare];

}

-(void)freshSymptomsDesc:(NSString *)title {
    
    UIFont *font = [UIFont systemFontOfSize:15];
    UIFont *txtfont = [UIFont systemFontOfSize:17];

    // 添加圆点
    NSString *bulletPoint = @"\u2022";
    NSString *bulletPointString = [NSString stringWithFormat:@"%@ ", bulletPoint];
    NSDictionary *bulletPointAttribute = @{NSParagraphStyleAttributeName: [NSParagraphStyle defaultParagraphStyle], NSFontAttributeName:font};
    
    NSAttributedString *bulletPointAttributedString = [[NSAttributedString alloc] initWithString:bulletPointString attributes:bulletPointAttribute];
    
    
    NSMutableAttributedString *totalAttreiString = [NSMutableAttributedString new];
    title = [title stringByAppendingString:@"\r\n"];
    NSAttributedString *titleAttri = [[NSAttributedString alloc] initWithString:title attributes:@{NSFontAttributeName : txtfont,
                    NSForegroundColorAttributeName : [UIColor whiteColor],}
                                 ];
    [totalAttreiString appendAttributedString:titleAttri];
    
    
    [self.ecgRecord.symptomsArray enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *itemString =  [DBEcgRecord titleOfSymptom:obj.integerValue];
        
        if (idx != self.ecgRecord.symptomsArray.count - 1) {
            itemString = [itemString stringByAppendingString:@"\r\n"];
        }
        // 创建一个NSMutableAttributedString
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:itemString attributes:@{NSFontAttributeName : txtfont,
                                                                                                                                NSForegroundColorAttributeName : [UIColor whiteColor],}];
        // 将圆点添加到文字前面
        [attributedString insertAttributedString:bulletPointAttributedString atIndex:0];
        [totalAttreiString appendAttributedString:attributedString];
    }];
  
    self.symptomsDescLbl.attributedText = totalAttreiString;
//    [self layoutIfNeeded];
    
}



-(void)initUI {
    
    [self arrowback:nil];
    self.navigationItem.title = _L(L_ECG_REC_DETAIL);//_L(L_BTN_ECG);
    
    QMUIButton *shareBtn = [[QMUIButton alloc]init];
    [shareBtn setImage:[UIImage imageNamed:@"main_share"] forState:UIControlStateNormal];
    [shareBtn addTarget:self action:@selector(exportPdf:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:shareBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    
    [self.view addSubview:self.scrollView];
    
    [self.scrollView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
    }];
    
    self.mainContent = [UIView new];
    self.topCnt = [UIView new];
    self.bottomCnt = [UIView new];
    
    self.topCnt.backgroundColor = ITEM_BG_COLOR;
    self.bottomCnt.backgroundColor = ITEM_BG_COLOR;

    [self.mainContent addSubview:self.topCnt];
    [self.mainContent addSubview:self.sampleTitleLbl];
    [self.mainContent addSubview:self.bottomCnt];
    
    [self.scrollView addSubview:self.mainContent];
    [self.mainContent mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mainContent.superview);
        make.centerX.equalTo(self.mainContent.superview.mas_centerX);
        make.width.equalTo(self.mainContent.superview.mas_width);
    }];
    
    [self.topCnt mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.equalTo(self.topCnt.superview);
    }];
    
    [self.sampleTitleLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topCnt.mas_bottom);
        make.leading.equalTo(self.topCnt.mas_leading).offset(15);
        make.trailing.equalTo(self.topCnt.mas_trailing).inset(0);
        make.height.equalTo(@40);
    }];
    
    [self.bottomCnt mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.bottomCnt.superview);
        make.top.equalTo(self.sampleTitleLbl.mas_bottom);
    }];
    
    [self layoutTopCnt];
    [self layoutBottomCnt];
    
    [self.mainContent addSubview:self.deletebtn];
    [self.deletebtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bottomCnt.mas_bottom).offset(15);
        make.centerX.equalTo(self.deletebtn.superview.mas_centerX);
        make.height.equalTo(@44);
        make.width.equalTo(self.deletebtn.superview.mas_width).multipliedBy(3/4.0);
        make.bottom.equalTo(self.deletebtn.superview.mas_bottom).inset(10);
    }];

}



/// 删除记录
/// - Parameter btn:btn
-(void)delRecord:(QMUIButton *)btn {
    
    WEAK_SELF
    [self showAlertWarningWithTitle:_L(L_TIP_DEL_ECG) Msg:_L(L_TXT_DEL_ECG) btnOk:_L(L_DELETE) OkBLk:^{
        STRONG_SELF
        [strongSelf.ecgRecord deleteFromTable:^{
            STRONG_SELF
            if (strongSelf.deleteCBK) {
                strongSelf.deleteCBK(strongSelf.ecgRecord);
            }
            
            [strongSelf.navigationController popViewControllerAnimated:YES];
            
        }];
        
    } CancelBtn:_L(L_CANCEL) CancelBlk:^{
        STRONG_SELF
        
        
    } Compelete:nil];
    
}


/// 显示结论信息
/// - Parameter btn:btn
-(void)gotoShowInfo:(UIButton *)btn {
   
}


/// 输出pdf
/// - Parameter btn:btn
-(void)exportPdf:(QMUIButton *)btn
{
    
    WEAK_SELF
    // 直接画图
    NSNumber *spType = @(HORIZONTAL_SPEED_DEFAULT);
    NSNumber *ygainType = @(VERTIAL_GAIN_DEFAULT);
    
    [self.pdfManager setHorizonalSpeed:spType.intValue VertialGain:ygainType.intValue Frequency:512 Direction:self.ecgRecord.wearHand]; // 固定值
    
    NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
    fmt.dateFormat = @"yyyy-MM-dd";
    NSDate *userBirth = [fmt dateFromString:@"2000-2-2"];
    
    [self.pdfManager createEcgSharePdfDrawInPdf:self.ecgRecord Frequency:512 Points:self.ecgRecord.volArray User:@"User name" Birthday:userBirth  Cmp:^(NSURL * _Nonnull pdfUrl) {
        STRONG_SELF
        [strongSelf shareUrl:pdfUrl];
        
    }];
    

    
}

-(void)shareUrl:(NSURL *)fileUrl {
    if (fileUrl == nil) {
        return;
    }
    
    NSArray *activityItems = @[fileUrl];
    UIActivityViewController *activityVc = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
    activityVc.excludedActivityTypes = @[UIActivityTypePrint];
    [self presentViewController:activityVc animated:YES completion:nil];
//    WEAK_SELF
    activityVc.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
//        STRONG_SELF
//        if (completed) {
//            [[LTPHud Instance] showText:@"share finish" Lasting:1.0];
//        }
    };
}

-(UIScrollView *)scrollView
{
    if(!_scrollView) {
        _scrollView = [UIScrollView new];
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    return _scrollView;
}

-(QMUIButton *)deletebtn
{
    if (!_deletebtn) {
        _deletebtn = [[QMUIButton alloc]init];
        _deletebtn.cornerRadius = ITEM_CORNOR_RADIUS;
        _deletebtn.backgroundColor = UIColor.whiteColor;
        [_deletebtn setTitleColor:BUTTON_RED forState:UIControlStateNormal];
        [_deletebtn addTarget:self action:@selector(delRecord:) forControlEvents:UIControlEventTouchUpInside];
        
        [_deletebtn setTitle:_L(L_ECG_DEL_REC) forState:UIControlStateNormal];
    }
    return _deletebtn;
}

-(QMUIButton *)pdfBtn
{
    if (!_pdfBtn) {
        _pdfBtn = [[QMUIButton alloc]init];
        [_pdfBtn setTitle:_L(L_EXPORT_PDF) forState:UIControlStateNormal];
        [_pdfBtn setTitleColor:MAIN_BLUE forState:UIControlStateNormal];
        [_pdfBtn addTarget:self action:@selector(exportPdf:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _pdfBtn;
}

-(ImgTitleItem *)hrItem
{
    if (!_hrItem) {
        _hrItem = [[ImgTitleItem alloc]init];
        _hrItem.imageView.image = [UIImage imageNamed:@"ecg_hr"];
        _hrItem.titleLbl.font = [UIFont fontWithName:FONT_ARIAL_BOLD size:17];
        
    }
    return _hrItem;
}

-(UILabel *)sampleTitleLbl
{
    if (!_sampleTitleLbl) {
        _sampleTitleLbl = [UILabel new];
        _sampleTitleLbl.font = [UIFont systemFontOfSize:20];
        _sampleTitleLbl.text = _L(L_ECG_SAMP_DETIL);
    }
    return _sampleTitleLbl;
}

-(UILabel *)emercallTipLbl
{
    if (!_emercallTipLbl) {
        _emercallTipLbl = [UILabel new];
        _emercallTipLbl.numberOfLines = 0;
        _emercallTipLbl.adjustsFontSizeToFitWidth = YES;
        _emercallTipLbl.textColor = UIColor.lightGrayColor;
        _emercallTipLbl.font = [UIFont systemFontOfSize:14];
        _emercallTipLbl.text = _L(L_ECG_DETAIL_EMERCALL_TIP);
    }
    return _emercallTipLbl;
}

-(SubTitleItem *)startTimeItem
{
    if (!_startTimeItem) {
        _startTimeItem = [self createItem];
        _startTimeItem.mainTitleLbl.text = _L(L_START_TIME);
    }
    return _startTimeItem;
}

-(SubTitleItem *)endTimeItem
{
    if (!_endTimeItem) {
        _endTimeItem = [self createItem];
        _endTimeItem.mainTitleLbl.text = _L(L_END_TIME);
    }
    return _endTimeItem;
}

-(SubTitleItem *)sourceItem
{
    if (!_sourceItem) {
        _sourceItem = [self createItem];
        _sourceItem.mainTitleLbl.text = _L(L_ECG_SOURCE);
    }
    return _sourceItem;
}
-(SubTitleItem *)firmwareItem
{
    if (!_firmwareItem) {
        _firmwareItem = [self createItem];
        _firmwareItem.mainTitleLbl.text = _L(L_DEV_FIRMWARE_VER);

    }
    return _firmwareItem;
}

-(LTRingEcgDrawHistoryView *)hisDrawLineView
{
    if (!_hisDrawLineView) {
        _hisDrawLineView = [[LTRingEcgDrawHistoryView alloc]init];
        NSNumber *spType = @(HORIZONTAL_SPEED_DEFAULT);
        NSNumber *ygainType = @(VERTIAL_GAIN_DEFAULT);
//        _hisDrawLineView.drawLineView.direction = [AccountCenter instance].currentAccount.otherInfo.wearHand.intValue;
//        _hisDrawLineView.gridView.showSeconds = YES;
        _hisDrawLineView.showSeconds = YES;
        _hisDrawLineView.gridView.secondUnitString = @"s";
        
        
        [_hisDrawLineView setHorizonalSpeed:spType.unsignedIntValue VertialGain:ygainType.unsignedIntValue];
        _hisDrawLineView.ecgLineColor = BUTTON_RED;
    }
    return _hisDrawLineView;
}
-(UILabel *)conclusionDescLbl
{
    if (!_conclusionDescLbl)
    {
        _conclusionDescLbl = [UILabel new];
        _conclusionDescLbl.numberOfLines = 0;
        _conclusionDescLbl.adjustsFontSizeToFitWidth = YES;
        _conclusionDescLbl.font = [UIFont fontWithName:FONT_ARIAL_BOLD size:16];
    }
    return _conclusionDescLbl;
}

-(UILabel *)symptomsDescLbl
{
    if (!_symptomsDescLbl)
    {
        _symptomsDescLbl = [UILabel new];
        _symptomsDescLbl.numberOfLines = 0;
        _symptomsDescLbl.adjustsFontSizeToFitWidth = YES;
//        _symptomsDescLbl.font = [UIFont fontWithName:FONT_ARIAL_BOLD size:16];
    }
    return _symptomsDescLbl;
}

@end



/// UI的部分
@implementation  EcgDetailVc (UI)

-(void)layoutTopCnt {
    
    UIButton *infoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [infoBtn setImage:[UIImage imageNamed:@"info"] forState:UIControlStateNormal];
    [infoBtn addTarget:self action:@selector(gotoShowInfo:) forControlEvents:UIControlEventTouchUpInside];
    [self.topCnt addSubview:infoBtn];
    self.infoBtn = infoBtn;
    
    if (self.ecgRecord.conclusion == CONCLUSION_NOT_ENOUGH_TIME) {
        self.infoBtn.hidden = YES;
    }
    
    self.topConcluLbl = [UILabel new];
    self.topConcluLbl.textAlignment = NSTextAlignmentLeft;
    
    self.topDateLbl = [UILabel new];
    self.topDateLbl.textAlignment = NSTextAlignmentLeft;
    [self.topCnt addSubview:self.topConcluLbl];
    [self.topCnt addSubview:self.topDateLbl];
    
    [self.topConcluLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.topConcluLbl.superview.mas_leading).offset(self.horMargin);
        make.top.equalTo(self.topConcluLbl.superview.mas_top).offset(10);
        make.height.equalTo(infoBtn.mas_height);
    }];
    
    [infoBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(infoBtn.superview.mas_trailing).inset(self.horMargin);
        make.centerY.equalTo(self.topConcluLbl.mas_centerY);
    }];
    
    [self.topDateLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topConcluLbl.mas_bottom).offset(5);
        make.leading.equalTo(self.topConcluLbl.mas_leading);
    }];
    
    UIView *drawCnt = [UIView new];
    [self.topCnt addSubview:drawCnt];
    CGFloat drawCntHeight = [self.hisDrawLineView.gridView historyTypeHeight];;
    [drawCnt mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(drawCnt.superview.mas_leading).offset(self.horMargin);
        make.trailing.equalTo(drawCnt.superview.mas_trailing).inset(self.horMargin);
        make.height.equalTo(@(drawCntHeight));
        make.top.equalTo(self.topDateLbl.mas_bottom).offset(8);
    }];
    
    [drawCnt addSubview:self.hisDrawLineView];
    [self.hisDrawLineView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.equalTo(self.hisDrawLineView.superview);
    }];
    
    
    
    
    [self.topCnt addSubview:self.hrItem];
    [self.hrItem mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(drawCnt);
        make.top.equalTo(drawCnt.mas_bottom).offset(25);
    }];
    
    SepLineView *sepHr = [self creatSepLine];
    [self.topCnt addSubview:sepHr];
    [sepHr mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.hrItem);
        make.top.equalTo(self.hrItem.mas_bottom).offset(5);
        make.height.equalTo(@1);
    }];
    
    [self.topCnt addSubview:self.conclusionDescLbl];
    [self.conclusionDescLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.hrItem);
        make.top.equalTo(sepHr.mas_bottom).offset(5);
        
    }];
    // 症状
    [self.topCnt addSubview:self.symptomsDescLbl];
    [self.symptomsDescLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.hrItem);
        make.top.equalTo(self.conclusionDescLbl.mas_bottom).offset(5);
    }];
    
    SepLineView *sepSymp = [self creatSepLine];
    [self.topCnt addSubview:sepSymp];
    [sepSymp mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.hrItem);
        make.top.equalTo(self.symptomsDescLbl.mas_bottom).offset(5);
        make.height.equalTo(@1);
    }];
    
    
    // pdf
    [self.topCnt addSubview:self.pdfBtn];
    [self.pdfBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.hrItem);
        make.top.equalTo(sepSymp.mas_bottom).offset(5);
        make.height.equalTo(@40);
    }];
    
    SepLineView *sepPdf = [self creatSepLine];
    [self.topCnt addSubview:sepPdf];
    [sepPdf mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.hrItem);
        make.top.equalTo(self.pdfBtn.mas_bottom).offset(5);
        make.height.equalTo(@1);
    }];
    
    [self.topCnt addSubview:self.emercallTipLbl];
    [self.emercallTipLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.hrItem);
        make.top.equalTo(sepPdf.mas_bottom).offset(5);
        make.bottom.equalTo(self.topCnt.mas_bottom).inset(10);
    }];

    
    
}

-(void)layoutBottomCnt
{
    NSArray<SubTitleItem *> *items = @[self.startTimeItem, self.endTimeItem, self.sourceItem, self.firmwareItem];
    [items enumerateObjectsUsingBlock:^(SubTitleItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.bottomCnt addSubview:obj];
    }];
    for (int i = 0; i < items.count; i++) {
        SubTitleItem *item = items[i];
        
        [item mas_remakeConstraints:^(MASConstraintMaker *make) {
            
            if (i == 0) {
                make.top.equalTo(item.superview.mas_top);
            } else {
                make.top.equalTo(items[i-1].mas_bottom);

            }
            make.leading.equalTo(item.superview.mas_leading).offset(self.horMargin);
            make.trailing.equalTo(item.superview.mas_trailing).inset(self.horMargin);
            make.height.equalTo(@50);
            
            if (i == items.count- 1) {
                make.bottom.equalTo(item.superview.mas_bottom);
            }
        }];
        
        
    }
    
    
}

-(SubTitleItem *)createItem 
{
    SubTitleItem *item = [[SubTitleItem alloc]init];
    
    return item;
}

-(SepLineView *)creatSepLine {
    SepLineView *sep = [[SepLineView alloc]init];
    sep.lineColor = SEPLINE_COLOR(0.7);
    sep.isDash = YES;
    return sep;
}


@end
